package language;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Student1 implements Serializable{
    private String name;
    private transient int age;
    private static int year = 2018;
    public Student1(){
        System.out.println("This is a constructor");
        this.name = "Krishna";
        this.age = 25;
    }
    public Student1(String name, int age){
        this.name = name;
        this.age = age;
    }
    public void display() {
        System.out.println("Name: "+this.name);
        System.out.println("Age: "+this.age);
        System.out.println("Year: "+Student1.year);
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public void setYear(int year) {
        Student1.year = year;
    }
}
public class SerializeExample{
    public static void main(String args[]) throws Exception{
        //创建 Student 对象
        Student1 std = new Student1("Vani", 27);
        //序列化对象
        FileOutputStream fos = new FileOutputStream("e:\\student.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(std);
        oos.close();
        fos.close();
        //在反序列化之前打印数据
        System.out.println("反序列化前的值");
        std.display();
        //更改静态变量值
        std.setYear(2019);
        //更改实例变量值
        std.setName("Varada");
        //更改瞬态变量值
        std.setAge(19);
        System.out.println("Object serialized.......");
        //反序列化对象
        FileInputStream fis = new FileInputStream("e:\\student.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);
        Student1 deSerializedStd = (Student1) ois.readObject();
        System.out.println("Object de-serialized.......");
        ois.close();
        fis.close();
        System.out.println("反序列化后的值");
        deSerializedStd.display();
    }
}